<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <el-row :gutter="5">
        <el-col :span="24" class="main-card-view">
          <el-row>
            <el-card shadow="never" class="top-search-view-card">
              <el-row>
                <el-form :inline="true" :model="searchForm" class="demo-form-inline search-view">
                  <el-form-item>
                    <el-button @click="grab">一键抓取
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-row>
            </el-card>
          </el-row>

          <el-row>
            <el-card shadow="never">
              <el-table :data="tableData" v-loading="loading" :stripe="true" style="width: 100%"
                @selection-change="handleSelection">
                <el-table-column prop="title" label="标题" width="400" />
                <el-table-column prop="origin" align="center" label="来源" />
                <el-table-column prop="coverFileName" align="center" label="封面">
                  <template slot-scope="scope">
                    <el-image style="width: 100px; height: 100px" :src="scope.row.coverFileName"
                      :preview-src-list="[scope.row.coverFileName]">
                    </el-image>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="200">
                  <template slot-scope="scope">
                    <!-- <el-button type="text" class="table-details-btn"
                      @click="handleDetails(scope.$index, scope.row)"></el-button> -->
                    <el-button type="text" class="table-details-btn"
                      @click="showEditDialog(scope.$index, scope.row)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <XPagination ref="pageInfo" :total="total" :get-data="getList" />
            </el-card>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog width="80%" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form label-width="120px" ref="form" :rules="formRules" :model="form">
        <el-form-item label="分类" prop="classify">
          <el-cascader v-model="form.classifyUid" :options="options" :props="props" placeholder="请选择"
            @change="handleChange" ref="cascader" style="width: 100%;"></el-cascader>
        </el-form-item>
        <el-form-item label="标题" prop="titleName">
          <el-input v-model="form.titleName" />
        </el-form-item>
        <!-- <el-form-item label="副标题" prop="subtitle">
                  <el-input v-model="form.subtitle"/>
              </el-form-item> -->
        <el-form-item label="关键字" prop="keyWork">
          <el-input v-model="form.keyWork" />
        </el-form-item>
        <el-form-item label="封面" prop="coverFileName">
          <x-upload v-model="form.coverFileName" />
        </el-form-item>
        <!-- <el-form-item label="摘要" prop="digest">
                  <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" v-model="form.digest"/>
              </el-form-item> -->
        <el-form-item label="内容" prop="contents">
          <MyEditor v-if="dialogVisible" v-model="form.contents"></MyEditor>
        </el-form-item>
        <el-form-item label="发布人" prop="publisher">
          <el-input v-model="form.publisher" disabled />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" />
        </el-form-item>
        <el-form-item label="来源" prop="origin">
          <el-input v-model="form.origin" />
        </el-form-item>
        <el-form-item label="位置" prop="positions">
          <el-checkbox-group v-model="form.positions">
            <el-checkbox label="首页" name="positions"></el-checkbox>
            <el-checkbox label="栏目首页" name="positions" disabled></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <el-input disabled v-model="form.releaseTime" />
        </el-form-item>
        <el-form-item label="是否栏目推荐" prop="columnRecommendation">
          <el-radio-group v-model="form.columnRecommendation">
            <el-radio label="否"></el-radio>
            <el-radio label="是"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否开启评论" prop="enableComments">
          <el-radio-group v-model="form.enableComments">
            <el-radio label="否"></el-radio>
            <el-radio label="是"></el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="排序号" prop="sort">
                  <el-input type="number" v-model="form.sort"></el-input>
              </el-form-item> -->
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog width="80%" title="详情" :visible.sync="realDialog">
      <el-form label-width="120px" :model="form" class="release-details">
        <el-form-item label="分类" prop="classify">
          <div>{{ form.classify }}</div>
        </el-form-item>
        <el-form-item label="标题" prop="titleName">
          <div>{{ form.titleName }}</div>
        </el-form-item>
        <!-- <el-form-item label="副标题" prop="subtitle">
                  <div>{{ form.subtitle }}</div>
              </el-form-item> -->
        <el-form-item label="关键字" prop="keyWork">
          <div>{{ form.keyWork }}</div>
        </el-form-item>
        <el-form-item label="封面" prop="coverFileName">
          <el-image style="width: 100px;height: 100px;" :src="form.coverFileName"></el-image>
        </el-form-item>
        <!-- <el-form-item label="摘要" prop="digest">
                  <div>{{ form.digest }}</div>
              </el-form-item> -->
        <el-form-item label="内容" prop="contents">
          <div id="real-editor-container"></div>
        </el-form-item>
        <el-form-item label="发布人" prop="publisher">
          <div>{{ form.publisher }}</div>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <div>{{ form.author }}</div>
        </el-form-item>
        <el-form-item label="来源" prop="origin">
          <div>{{ form.origin }}</div>
        </el-form-item>
        <el-form-item label="位置" prop="positions">
          <el-checkbox-group :value="form.positions">
            <el-checkbox label="首页" name="positions"></el-checkbox>
            <el-checkbox label="栏目首页" name="positions"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <div>{{ form.releaseTime }}</div>
        </el-form-item>
        <el-form-item label="是否栏目推荐" prop="columnRecommendation">
          <el-radio-group :value="form.columnRecommendation">
            <el-radio label="否"></el-radio>
            <el-radio label="是"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否开启评论" prop="enableComments">
          <el-radio-group :value="form.enableComments">
            <el-radio label="否"></el-radio>
            <el-radio label="是"></el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="排序号" prop="sort">
                  <div>{{ form.sort }}</div>
              </el-form-item> -->
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="realDialog = false">关闭</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import XPagination from "../../components/xpagination/XPagination"
import * as topMessage from "../../api/topMessage"
import * as DataAcquisition from "../../api/DataAcquisition"

import XUpload from "../../components/xupload/XUpload"
import request from '../../utils/request'
import axios from 'axios'
import MyEditor from '../../components/vueUeditor.vue'
import * as classifyManger from "../../api/classifyManger";
import { handleTreeData } from "../../utils/tree";
export default {
  components: { XUpload, XPagination, MyEditor },
  data () {
    return {
      searchForm: {

      },
      tableData: [],
      loading: false,
      dialogVisible: false,
      realDialog: false,
      total: 0,
      dialogTitle: "添加发布",
      form: {
        positions: ['栏目首页']
      },
      editStatus: "add",
      formRules: {
        classify: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        titleName: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        subtitle: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        keyWork: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        coverFileName: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        digest: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        contents: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        publisher: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        // origin: [
        //     {required: true, message: '不能为空', trigger: 'blur'},
        // ],
        // positions: [
        //     {required: true, message: '不能为空', trigger: 'blur'},
        // ],
        releaseTime: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        columnRecommendation: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        enableComments: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
      },
      editor: null,
      options: [],
      props: {
        value: 'uid',
        label: 'classifyName',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      selectedRows: [],
      userInfo: {},
      loading: false
    }
  },
  methods: {
    getList (pageInfo) {
      const param = {
        ...this.searchForm,
        ...pageInfo,
        recycleType: '0'
      }
      if (param.status == '0' || param.status == '') {
        param.status = ''
      }
      topMessage.queryByPage(param).then(response => {
        console.log(response)
        this.tableData = response.data.data.rows
        this.total = response.data.data.total
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },
    handleDelete (index, data) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        if (data.status === '未审核') {
          topMessage.deleteById(data.uid).then(result => {
            this.loading = false
            this.$message.success(result.data.msg)
            this.handleSearch()
          }).catch(error => {
            this.loading = false
            console.log(error)
          })
        } else {
          let param = {
            userId: this.userInfo.uid,
            entities: [{
              uid: data.uid,
              recycleType: '1'
            }]
          }
          classifyManger.batchDel(param).then(res => {
            if (res.data.code == 200) {
              this.loading = false
              this.$message.success(res.data.msg)
              this.handleSearch()
            }
          }).catch(error => {
            this.loading = false
            console.log(error)
          })
        }
      }).catch(() => {
        console.log('取消删除')
      });
    },
    handleSearch () {
      this.$refs.pageInfo.loadData()
    },
    showCreateDialog () {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.getTree()
        this.getDefaltTreeNode("头条资讯");
        this.dialogTitle = "添加发布"
        this.editStatus = "add"
        this.$refs.form.resetFields()
        this.form = Object.assign({}, this.$options.data().form)
        this.form.releaseTime = this.moment().format("YYYY-MM-DD HH:mm:ss")
        this.form.publisher = localStorage.getItem("username")
        this.form.publisherUid = localStorage.getItem("loginUid")
        this.$set(this.form, 'columnRecommendation', '否')
        this.$set(this.form, 'enableComments', '否')
      })
    },
    handleSave () {
      if (this.form.positions.includes('首页')) {
        this.form.positionsOne = '首页'
      } else {
        this.form.positionsOne = '1'
      }
      if (this.form.positions.includes('栏目首页')) {
        this.form.positionsTwo = '栏目首页'
      } else {
        this.form.positionsTwo = '1'
      }
      this.handleAdd()
      // if (this.editStatus === "add") {
      //   this.handleAdd()
      // } else {
      //   this.handleEdit()
      // }
    },
    handleAdd () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = Object.assign({}, this.form)
        param.coverFileName = '123'
        topMessage.insert(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          //this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })

      })
    },
    handleEdit () {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false
        }
        const param = Object.assign({}, this.form)
        topMessage.update(param).then(result => {
          this.$message.success(result.data.msg)
          this.dialogVisible = false
          this.handleSearch()
        }).catch(error => {
          this.$message.error(error)
          console.log(error)
        })
      })
    },
    showEditDialog (index, data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['form'].resetFields()
        this.form = Object.assign({}, data)
        this.$set(this.form, 'positions', [])
        // if (this.form.positionsOne == '首页') {
        //   this.form.positions.push('首页')
        // }
        // if (this.form.positionsTwo == '栏目首页') {
        //   this.form.positions.push('栏目首页')
        // }
        this.getTree()
        this.form.titleName = this.form.title
        this.form.releaseTime = this.moment().format("YYYY-MM-DD HH:mm:ss")
        this.form.publisher = localStorage.getItem("username")
        this.form.publisherUid = localStorage.getItem("loginUid")
        this.form.columnRecommendation = '否'
        this.form.enableComments = '否'
        delete this.form.createTime
        delete this.form.updateTime
        this.dialogTitle = "编辑发布"
        this.editStatus = "edit"
      })
    },
    handleDetails (index, data) {
      this.realDialog = true
      this.$nextTick(() => {
        this.getTree()
        this.form = Object.assign({}, data)
        this.$set(this.form, 'positions', [])
        if (this.form.positionsOne == '首页') {
          this.form.positions.push('首页')
        }
        if (this.form.positionsTwo == '栏目首页') {
          this.form.positions.push('栏目首页')
        }
        document.getElementById('real-editor-container').innerHTML = this.form.contents
        let video = document.getElementsByTagName('video')
        for (var i = 0; i < video.length; i++) {
          video[i].parentElement.style.display = 'flex'
          video[i].parentElement.style.justifyContent = 'center'
        }
      })
    },
    // 树节点
    getTree (classifyName) {
      const param = {
        classifyName
      };
      classifyManger.queryByClassifyName(param).then(response => {
        this.options = handleTreeData(response.data.data)
      }).catch(error => {
        console.log(error)
      })
    },

    getDefaltTreeNode (classifyName) {
      const param = {
        classifyName
      };
      classifyManger.queryOne(param).then(response => {
        this.form.classifyUid = response.data.data.uid
        setTimeout(() => {
          this.$nextTick(() => {
            this.form.classify = this.$refs.cascader.presentText;
            console.log(this.form.classify)
          })
        }, 1000)
      }).catch(error => {
        console.log(error)
      })
    },

    handleChange (value) {
      this.$nextTick(() => {
        this.$refs.cascader.dropDownVisible = false
        this.form.classify = this.$refs.cascader.presentText;
      })
    },
    handleSelection (selection) {
      this.selectedRows = selection;
    },
    grab () {
      this.loading = true
      DataAcquisition.getCrawlContents({}).then(response => {
        this.tableData = response.data.data.rows
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.log(error)
      })
    },
    isSelectable (row, index) {
      if (row.status === '审核中') {
        return false
      } else if (row.status === '已审核') {
        if (this.userInfo.roleName === '管理员' || this.userInfo.roleName === '运营人员') {
          return true
        } else {
          return false
        }
      } else {
        return true
      }
    }
  },
  mounted () {
    this.userInfo = JSON.parse(localStorage.getItem('user_info'))
    //this.handleSearch()
  }
}
</script>

<style scoped lang="scss"></style>
